package com.opages.transaction.message.common.utils;


import com.opages.transaction.message.common.domain.HttpResult;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientTool {

	private static final Logger log = LoggerFactory.getLogger(HttpClientTool.class);

	//连接超时时间，默认10秒
    private static final int socketTimeout = 10000;

    //传输超时时间，默认30秒
    private static final int connectTimeout = 30000;

	/**
	 * 发送一个POST请求，返回String对象
	 * @param url		发送数据的网址
	 * @param params	POST请求的参数
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public final static String postString(String url, Map<String, Object> params) throws Exception {
		HttpPost httppost = new HttpPost(url);
		List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
		if(params != null) {
			for (String key : params.keySet()) {
				valuePairs.add(new BasicNameValuePair(key, params.get(key)== null ? "" : params.get(key).toString()));
			}
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, "UTF-8");
		httppost.setEntity(entity);
		System.out.println("executing request " + httppost.getRequestLine());
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = httpclient.execute(httppost);

		String responseText = null;
        log.info("Http Status Code: " + response.getStatusLine().getStatusCode());
		if (response.getStatusLine().getStatusCode() == 200) {
			responseText = EntityUtils.toString(response.getEntity());
            log.info("response: " + responseText);
		}

		response.close();
		httppost.releaseConnection();
		return responseText;
	}
	/**
	 * 发送一个POST请求，返回String对象
	 * @param url		发送数据的网址
	 * @param params	POST请求的参数
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public final static CloseableHttpResponse postMap(String url, Map<String, Object> params){
		HttpPost httppost = new HttpPost(url);
		CloseableHttpResponse response = null;
		try{
			/*UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, "UTF-8");
			httppost.setEntity(entity);*/
			if (params != null) {
				// 构造一个form表单式的实体
				StringEntity stringEntity = new StringEntity(JSONObject.fromObject(params).toString(), ContentType.APPLICATION_JSON);
				// 将请求实体设置到httpPost对象中
				httppost.setEntity(stringEntity);
			}
			CloseableHttpClient httpclient = HttpClients.createDefault();
			response = httpclient.execute(httppost);
			return response;
		}catch(Exception e){
			e.printStackTrace();
			log.info("http请求异常"+e);
		}finally {
			if(null!=response){
				try {
					response.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			httppost.releaseConnection();
		}
		return response;
	}
	/**
	 * 提交json数据
	 *
	 * @param url
	 * @param json
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static HttpResult doPostJson(String url, String json)  {
		// 创建http POST请求
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpResponse response = null;
		if (json != null) {
			// 构造一个form表单式的实体
			StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
			// 将请求实体设置到httpPost对象中
			httpPost.setEntity(stringEntity);
		}
		try {
			// 执行请求
			CloseableHttpClient httpclient = HttpClients.createDefault();
			response = httpclient.execute(httpPost);
			return new HttpResult(response.getStatusLine().getStatusCode(),
					EntityUtils.toString(response.getEntity(), "UTF-8"));
		}catch(Exception e){
			e.printStackTrace();
			log.info("http请求异常|"+e);
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		//return response;
		return null;
	}

	/**
	 * 发送一个POST请求，返回String对象
	 * @param url   请求地址
	 * @param xmlStr  xml格式string类型参数
	 * @return
	 * @throws Exception
	 */
	public final static String postStringXml(String url, String xmlStr) throws Exception {
		HttpPost post = new HttpPost(url);
		StringEntity postEntity = new StringEntity(xmlStr, "UTF-8");
		post.addHeader("Content-Type", "text/xml");
		post.setEntity(postEntity);
		//根据默认超时限制初始化requestConfig
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
				.setConnectTimeout(connectTimeout).build();
		//设置请求器的配置
        post.setConfig(requestConfig);

        CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = httpclient.execute(post);
        HttpEntity entity = response.getEntity();

		return EntityUtils.toString(entity, "UTF-8");
	}

	public final static String postString(String url, Map<String, Object> params, String backCharset) throws Exception {
		return new String(postString(url, params).getBytes(backCharset));
	}

	/**
	 * 发送一个POST请求，返回JSONObject对象
	 * @param url		发送数据的网址
	 * @param params	POST请求的参数
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public final static String postJson(String url, Map<String, Object> params) throws Exception {
		return postString(url, params);
	}

	/**
	 * 发送一个POST请求，返回String对象
	 * @param url		发送数据的网址
	 * @param body		POST请求的数据域
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public final static String multiPartPostString(String url, String body) throws Exception {
		HttpPost httppost = new HttpPost(url);

		httppost.setEntity(new StringEntity(body, "UTF-8"));
		System.out.println("executing request " + httppost.getRequestLine());
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = httpclient.execute(httppost);

		System.out.println("----------------------------------------");
		String responseText = null;
		if (response.getStatusLine().getStatusCode() == 200) {
			responseText = EntityUtils.toString(response.getEntity());
		}

		response.close();
		httppost.releaseConnection();
		return responseText;
	}

	/**
	 * 发送一个POST请求，返回JSONObject对象
	 * @param url		发送数据的网址
	 * @param body	POST请求的参数
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public final static JSONObject multiPartPostJson(String url, String body) throws Exception {
		String response = multiPartPostString(url, body);
		return JSONObject.fromObject(response);
	}

	/**
	 * 发送一个GET请求，返回String对象
	 * @param url	请求地址
	 * @return
	 * @throws Exception
	 */
	public final static String getString(String url) throws Exception {
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = httpclient.execute(httpGet);

		String responseText = null;
		if (response.getStatusLine().getStatusCode() == 200) {
			responseText = EntityUtils.toString(response.getEntity());
		}

		response.close();
		httpGet.releaseConnection();
		return responseText;
	}

	/**
	 * 发送一个GET请求，返回JSONObject对象
	 * @param url	请求地址
	 * @return
	 * @throws Exception
	 */
	public final static JSONObject getJson(String url) throws Exception {
		return JSONObject.fromObject(getString(url));
	}

	/**
	 * 发送一个GET请求，返回解析了对应字符集的JSONObject对象
	 * @param url
	 * @param backCharset
	 * @return
	 * @throws Exception
	 */
	public final static JSONObject getJson(String url, String backCharset) throws Exception {
		return JSONObject.fromObject(new String(getString(url).getBytes(backCharset)));
	}

    /**
     *
     * @param retryTimes    重试次数
     * @param url           请求地址
     * @param account       用于校验用户名
     * @param pswd          用于校验密码
     * @param mobile        手机号
     * @param msg           短信消息内容
     * @param needstatus    是否需要返回状态
     * @param product       产品ID
     * @param extno         扩展码
     * @return              返回发送成功日期加状态码的String
     * @throws Exception
     */
	public static String sendHttpRequest4Sms(int retryTimes, String url, String account, String pswd, String mobile, String msg, boolean needstatus, String product, String extno) throws Exception {
		HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
        client.getHttpConnectionManager().getParams().setSoTimeout(5000);
        client.getHttpConnectionManager().getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpRequestRetryHandler(retryTimes, retryTimes != 0));
		GetMethod method = new GetMethod();

		try {
			URI base = new URI(url, false);
			method.setURI(new URI(base, "HttpBatchSendSM", false));
			method.setQueryString(new org.apache.commons.httpclient.NameValuePair[]{
                    new org.apache.commons.httpclient.NameValuePair("account", account),
                    new org.apache.commons.httpclient.NameValuePair("pswd", pswd),
                    new org.apache.commons.httpclient.NameValuePair("mobile", mobile),
                    new org.apache.commons.httpclient.NameValuePair("needstatus", String.valueOf(needstatus)),
                    new org.apache.commons.httpclient.NameValuePair("msg", msg),
                    new org.apache.commons.httpclient.NameValuePair("product", product),
                    new org.apache.commons.httpclient.NameValuePair("extno", extno)});
			int result = client.executeMethod(method);
			if(result != 200) {
				throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
			} else {
				InputStream in = method.getResponseBodyAsStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];

				int len1;
				while((len1 = in.read(buffer)) != -1) {
					baos.write(buffer, 0, len1);
				}

				return URLDecoder.decode(baos.toString(), "UTF-8");
			}
		} finally {
			method.releaseConnection();
		}
	}
	/**
	 * @Description: 调消息系统接口发送消息
	 * @Author ganyx
	 * @param uuid 判断校验是否成功
	 * @param msgBody 调用参数
	 * @param sendUrl 调用接口
	 * @param consumerQueue 消费的队列
	 * @throws Exception
	 */
	/*public static <T extends BaseModel<?>> HttpResultCdy sendMessage(T msg ,String sendUrl) throws Exception{
		TransactionMessage msg = new TransactionMessage();
		msg.setUuid(uuid);
		msg.setConsumerQueue(consumerQueue);
		msg.setMessageBody(JSONUtil.toJson(msgBody));
		msg.setMsgConfirmUrl(msgConfirmUrl);
		return doPostJson(sendUrl, JSONUtil.toJson(msg));
	}*/
}
